import http from './http'

// POST /intelligent-login/role/page
// body: { pageNum, pageSize, keyword, status }
export function pageRoles(data) {
  return http.post('/intelligent-login/role/page', data)
}

// GET /intelligent-login/role/detail?id=
export function getRoleDetail(id) {
  return http.get('/intelligent-login/role/detail', { params: { id } })
}

// POST /intelligent-login/role
export function createRole(data) {
  return http.post('/intelligent-login/role', data)
}

// PUT /intelligent-login/role
export function updateRole(data) {
  return http.put('/intelligent-login/role', data)
}

// DELETE /intelligent-login/role?id=
export function deleteRole(id) {
  return http.delete('/intelligent-login/role', { params: { id } })
}

// GET /intelligent-login/role/permissions?roleId=
export function getRolePermissions(roleId) {
  return http.get('/intelligent-login/role/permissions', { params: { roleId } })
}

// PUT /intelligent-login/role/permissions
// body (by ID): { roleId, permissionIds: [] }
// also accepts legacy: { roleId, permissions: [] }
export async function updateRolePermissions(data) {
  try {
    // 一些环境仅允许 GET，此处先尝试 PUT，若 405 则回退为 GET
    return await http.put('/intelligent-login/role/permissions', data, { showError: false })
  } catch (err) {
    if (err?.response?.status === 405) {
      const params = {}
      if (data && data.roleId != null) params.roleId = data.roleId
      if (Array.isArray(data?.permissionIds) && data.permissionIds.length) params.permissionIds = data.permissionIds
      if (Array.isArray(data?.permissions) && data.permissions.length) params.permissions = data.permissions
      return http.get('/intelligent-login/role/permissions', { params })
    }
    throw err
  }
}

// ===== Permission catalog (backend-driven) =====
// Prefer a grouped endpoint if available, otherwise fall back to flat list.
// You can wire either of these two paths on the backend. The component
// will try groups first, then flat.

// GET (recommended) e.g. /intelligent-login/permission/groups
// Expected response.data.data example:
// [ { groupId: 1, groupName: '商品管理', children: [ { id: 101, name: '新建商品' }, ... ] }, ... ]
export function listPermissionGroups() {
  return http.get('/intelligent-login/permission/groups')
}

// GET (fallback) e.g. /intelligent-login/permission/list
// Expected response.data.data example (flat):
// [ { id: 101, name: '新建商品', groupName: '商品管理' }, ... ]
export function listPermissionsFlat() {
  return http.get('/intelligent-login/permission/list')
}
